<template>
  <div class="container">
    <el-card shadow="never">
      <template #header>
        <div style="display:flex;align-items:center;gap:12px;">
          <span>{{ isEdit ? '编辑文章' : '发布新文章' }}</span>
          <div style="flex:1;"></div>
          <el-button @click="$router.back()">返回</el-button>
          <el-button type="primary" :loading="submitting" @click="onSubmit">{{ isEdit ? '保存修改' : '发布' }}</el-button>
        </div>
      </template>

      <el-form ref="formRef" :model="form" :rules="rules" label-width="108px">
        <el-form-item label="文章标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="文章分类" prop="category">
          <el-select v-model="form.category" placeholder="选择分类">
            <el-option v-for="c in categories" :key="c.name" :label="c.name" :value="c.name" />
          </el-select>
        </el-form-item>
        <el-form-item label="文章摘要" prop="summary">
          <el-input type="textarea" v-model="form.summary" :rows="3" placeholder="简要描述" />
        </el-form-item>
        <el-form-item label="文章正文" prop="content">
          <el-input type="textarea" v-model="form.content" :rows="10" placeholder="支持 HTML 片段或纯文本" />
        </el-form-item>
        <el-form-item label="封面图链接">
          <el-input v-model="form.cover" placeholder="封面图 URL（可选）" />
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { onMounted, reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { fetchCategories, fetchPostById, savePost } from '@/services/blogService'
import { getCurrentUser, isLoggedIn } from '@/services/userService'

const route = useRoute()
const router = useRouter()
const isEdit = !!route.params.id

const formRef = ref()
const defaultCover = 'https://images.unsplash.com/photo-1498050108023-c5249f4df085?q=80&w=1200&auto=format&fit=crop'
const form = reactive({
  id: undefined,
  title: '',
  category: '',
  summary: '',
  content: '',
  cover: defaultCover,
  date: '',
  tags: [],
})

const rules = {
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  summary: [{ required: true, message: '请输入摘要', trigger: 'blur' }],
  content: [{ required: true, message: '请输入正文内容', trigger: 'blur' }],
  category: [{ required: true, message: '请选择分类', trigger: 'change' }],
}

const categories = ref([])
const submitting = ref(false)

onMounted(async () => {
  // 检查登录状态
  if (!isLoggedIn()) {
    ElMessage.warning('请先登录')
    return router.push('/login')
  }
  
  categories.value = await fetchCategories()
  
  if (isEdit) {
    const p = await fetchPostById(route.params.id)
    if (!p) {
      ElMessage.error('文章不存在')
      return router.replace('/')
    }
    
    // 检查是否为文章作者
    const currentUser = getCurrentUser()
    if (p.authorId && p.authorId !== currentUser.id) {
      ElMessage.error('只能编辑自己的文章')
      return router.push('/')
    }
    
    Object.assign(form, {
      id: p.id,
      title: p.title,
      category: p.category,
      summary: p.summary,
      content: p.content,
      cover: p.cover || defaultCover,
      date: p.date,
      tags: p.tags || [],
    })
  }
})

function onSubmit() {
  formRef.value.validate(async (ok) => {
    if (!ok) return
    submitting.value = true
    
    try {
      if (isEdit) {
        await savePost({ ...form })
        ElMessage.success('文章修改已保存')
        router.push(`/article/${form.id}`)
      } else {
        const now = new Date().toISOString().slice(0, 10)
        const newPost = { 
          ...form, 
          publishedAt: now, 
          views: 0,
          cover: form.cover || defaultCover
        }
        await savePost(newPost)
        ElMessage.success('文章发布成功')
        router.push('/')
      }
    } catch (error) {
      ElMessage.error(error.message || '操作失败')
    } finally {
      submitting.value = false
    }
  })
}
</script>


